package com.github.chirspan.xaas.security.config;

import com.github.chirspan.xaas.core.constant.SecurityConstants;
import com.github.chirspan.xaas.security.service.AuthUserDetail;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author ChenPan
 * @date 2018/7/6 14:47
 * description: 自定义令牌信息
 */
@Component
public class CustomTokenEnhancer implements TokenEnhancer {

    @Override
    public OAuth2AccessToken enhance(
            OAuth2AccessToken accessToken,
            OAuth2Authentication authentication) {
        Map<String, Object> additionalInfo = new HashMap<>();
        AuthUserDetail user = (AuthUserDetail) authentication.getUserAuthentication().getPrincipal();
        additionalInfo.put(SecurityConstants.JWT_USER_ID, user.getId());
       /* Set<String> authorities = new HashSet<>();
        authentication.getAuthorities().stream().forEach(a -> authorities.add(((GrantedAuthority) a).getAuthority()));
        additionalInfo.put("authorities", authorities);*/
        ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
        return accessToken;
    }
}
